<?
require "../inc/rwINIfile.php";

$shareDir = "/var/shares/";
$shareList = array();

function getPerms($file)
{
	$owner = '';
	$group = '';
	$perms = array();

	// läser rättigheter
	exec('/usr/bin/getfacl --numeric '.$file.' 2> /dev/null', $out);
	// skapar array med ( användare/grupp -> rättigheter )
	foreach( $out AS $line ) {
		  //läser in ägaren
		if( preg_match('/^# owner: (.*)/', $line, $matches) )
			$owner = $matches[1];
		  //läser in gruppen
		if( preg_match('/^# group: (.*)/', $line, $matches) )
			$group = $matches[1];
		  //läser in rättighet
		else if( preg_match('/^([^:]*:[^:]*):(.*)/', $line, $matches) ) {
			$name = $matches[1];
			$perm = $matches[2];
			
			//om ägaren är root ska dennes rättigheter ej visas
			if( preg_match('/^user:$/', $name) ) {
				if( $owner == '0' )
					continue;
				else
					$name = $name.$owner;
			}
			//om ägargruppen är root ska dennes rättigheter ej visas
			if( preg_match('/^group:$/', $name) ) {
				if( $group == '0' )
					continue;
				else
					$name = $name.$group;
			}
			//om mask är satt ska denna ej visas
			if( preg_match('/^mask:$/', $name) )
				continue;
			//defaultregler visas ej
			if( preg_match('/^default:/', $name) )
				continue;
			//om användaren www-data har rättigheter så ska dessa ej visas
			$wwwdata = posix_getpwnam('www-data');
			if( preg_match('/^user:'.$wwwdata['uid'].'$/', $name) )
				continue;

			//spara rättigheterna i array
			$perms[$name] = $perm;
		}
	}

	return $perms;
}


function createSharelist()
{
	global $shareDir;
	global $shareList;
	$shareList = array();

	$dh  = opendir($shareDir);
	while (false !== ($thing = readdir($dh))) {
		if (is_dir("$shareDir$thing") && $thing != "." && $thing != "..") {
			$arr = array();
			$arr["owner"] = fileowner("$shareDir$thing");
			$arr["grp"] = filegroup("$shareDir$thing");
			$arr["perms"] = getPerms("$shareDir$thing");
			$shareList[$thing] = $arr;
		}
	}
}


function show() {
	global $shareDir;
	global $shareList;

                //kolla om en site har blivit klickad på eller ska skapas-> visa och tillåt editering
        if(isset($_GET["show"]) || isset($_GET["new"])) {
		if( isset($_GET["show"]) ) {
			if (!isset($shareList[$_GET["show"]])) {
                        	error('map_dont_exist');
                        	return;
			}
			$name = $_GET["show"];
                	$share = $shareList[$name];
                }
		else {
			if( isset( $shareList[ $_GET["new"] ] ) ) {
				error('map_exist');
				return;
				//$share = $shareList[ $_GET["new"] ];
			}
			$name = $_GET["new"];
		}

               
	       		//hämta andvändardata
                $ldap = ldapConnect();
                $grparr = getLdapGroups($ldap);
		$userarr = getLdapUsers($ldap);
                ldapClose($ldap);

		$perms = $share["perms"];
                
			
                echo '<input type="hidden" name="name" value="'.$name.'">';
	
		echo "<table cellspacing=\"0\"><tr><td class=\"tbhead\" colspan=2>Användare / grupper</td><td class=\"tbhead\">rättigheter</td><td class=\"tbhead\">&nbsp;</td></tr>";

		//placera 'other:' sist i $perms array
		if( array_key_exists('other:', $perms) ) {
			$perm = $perms['other:'];
			unset($perms['other:']);
			$perms['other:'] = $perm;
		}
		//skriv ut alla rättigheter på katalogen
		foreach( $perms AS $usergroup => $perm ) {
			if( preg_match('/^user:(.*)/', $usergroup, $match) ) {
				$uid = posix_getpwuid($match[1]);
				$str = '<td style="text-align: center; width:24px"><img src="/images/user.png" alt="Användare:"></td><td>'.$uid['name'].'</td>';
			}
			else if( preg_match('/^group:(.*)/', $usergroup, $match) ) {
				$gid = posix_getgrgid($match[1]);
				$str = '<td style="text-align: center; width:24px"><img src="/images/users.png" alt="Grupp:"></td><td>'.$gid['name'].'</td>';
			}
			else if( preg_match('/^other:$/', $usergroup, $match) ) {
				if( sizeof($perms) > 1 )
					$str = '<td style="text-align: center; width:24px"><img src="/images/users.png" alt="Grupp:"></td><td>Övriga</td>';
				else
					$str = '<td style="text-align: center; width:24px"><img src="/images/users.png" alt="Grupp:"></td><td>Alla</td>';
			}
			else {
				$str = '<td style="text-align: center; width:24px">&nbsp;</td>Okänd typ: '.$usergroup.'</td>';
			}

			echo "<tr ".help('show_acl_usergroup').">$str";

			echo "<td><select name=\"perm_$usergroup:\">";
			switch($perm) {
			case 'rwx':
				echo "<option value=\"rwX\" selected>Skriva och läsa filer";
				echo "<option value=\"r-X\">Enbart läsa filer";
				echo "<option value=\"---\">Ingen behörighet";
				break;
			case 'r-x':
				echo "<option value=\"rwX\">Skriva och läsa filer";
				echo "<option value=\"r-X\" selected>Enbart läsa filer";
				echo "<option value=\"---\">Ingen behörighet";
				break;
			case '---':
				echo "<option value=\"rwX\">Skriva och läsa filer";
				echo "<option value=\"r-X\">Enbart läsa filer";
				echo "<option value=\"---\" selected>Ingen behörighet";
				break;
			default:
				echo "<option value=\"rwX\">Skriva och läsa filer";
				echo "<option value=\"r-X\">Enbart läsa filer";
				echo "<option value=\"---\">Ingen behörighet";
				echo "<option value=\"".$perm."\" selected>Special";
				break;
			}
			echo "</select></td>";

			if( !preg_match('/^other:$/', $usergroup, $match) )
				echo '<td><a href="/main.php?s=samba&amp;show='.$name.'&amp;removeacl='.$usergroup.'&amp;do=1"><img src="/images/delete.png" alt="Ta bort"></td>';
			else
				echo "<td>&nbsp;</td>";
			echo "</tr>";

		}
		echo '</table><br>';
		echo '<table cellspacing="0" style="border: 1px solid #bbb; padding: 0.5em;" '.help('show_newacl_usergroup').'>';
		echo '<tr><td colspan=5><b>Ny behörighet</b></td></tr>';
		echo "<tr><td colspan=2><select name=\"new\">";
		echo "<option value=\"\">&nbsp;";
                echo "<option value=\"Användare:\" style=\"background-color:#ada;font-weight: 900\">Användare:";
		foreach($userarr as $user) {
			$username = $user["cn"][0];
			$usernr = $user["uidnumber"][0];
			echo "<option value=\"u$usernr\" style=\"background-color:#cfc;\">$username";
		}
                echo "<option value=\"\" style=\"background-color:#aad;font-weight: 900\">Grupper:";
                foreach($grparr as $group) {
	                $grpname = $group["cn"][0];
	                $grpnr = $group["gidnumber"][0];
                	echo "<option value=\"g$grpnr\" style=\"background-color:#ccf;\">$grpname";
        	}
		echo "</select></td>";
		echo "<td><select name=\"permnew\">";
		echo "<option value=\"rwX\" selected>Skriva och läsa filer";
		echo "<option value=\"r-X\">Enbart läsa filer";
		echo "<option value=\"---\">Ingen behörighet";
		echo '</select></td><td><input type="submit" name="b_create" class="button" value="Lägg till"></td></tr>';
		echo "</table><br>";
        }
}


function showAll()
{
	global $shareDir;
	global $shareList;
	
	$i=0;
	echo '<table cellspacing="0">';
	echo "<tr>";
	echo "  <td class=\"tbhead\">utdelade kataloger</td>";
	echo "  <td class=\"tbhead\">&nbsp</td>";
	echo "</tr>";
	foreach ($shareList as $name => $share) {
		$i++;
		echo "<tr ".($i%2==1?"class='list1'":"class='list2'").">\n";
		echo "  <td onClick=\"location = '?s=samba&show=$name'\" ".help('showall_map_name')."><a href=\"?s=samba&show=$name\">$name</a></td>";
		echo "	<td><a href=\"?s=samba&remove=$name&do=1\" ".confirm('map_remove')." ".help('showall_map_remove')."><img src=\"/images/delete.png\" border=0></a></td>";
		echo "</tr>";
	}
	echo "</table><br/>";
	
	echo '<table cellspacing="0" style="border: 1px solid #bbb;padding: 0.5em;">';
	echo "<tr><td><b>Skapa ny delad katalog</b></td></tr>";
	echo "  <tr ".help('showall_map_new').">";
	echo "    <td>namn: ";
	echo "        <input class=\"input-box\" type=\"text\" name=\"new\" value=\"\">";
	echo "        <input type=\"submit\" name=\"b_new\" value=\"skapa\" class=\"button\" /></td>";
	echo "  </tr>";
	echo "</table><br/>";
}




  //kontrollera mappar som ska ligga för utdelning
createSharelist();

if( isset($_GET['show']) AND $_GET['show'] ) {
	html_start(array( array('map',$_GET['show']) ));
	show();
	html_end(true, true, true, 'samba');
}
else {
	html_start(array( array('map','Fildelning') ));
	showAll();
	html_end();
}

?>
